import functools
import typing
from typing import Optional, List
from fastapi import BackgroundTasks


class BackgroundTasksDependencyInject:

    def __init__(self, only_run_first: bool = True) -> None:
        # 访问路由组时候是否仅仅执行一次后台任务
        self.only_run_first: bool = only_run_first
        # 后台任务
        self.background_task = None
        # 存放任务列表
        self.tasks: Optional[List[typing.Callable]] = []

    def add_task(self, function=None, *args, **kwargs) -> None:
        if function:
            func_obj = functools.partial(function, *args, **kwargs)
            self.tasks.append(func_obj)

    def on_task(self, *args, **kwargs) -> typing.Callable:  # pragma: nocover
        def decorator(func: typing.Callable) -> typing.Callable:
            self.add_task(func, *args, **kwargs)
            return func

        return decorator

    async def __call__(self, background_task: BackgroundTasks) -> Optional[BackgroundTasks]:
        """
        """
        pass
        if not self.background_task:
            self.background_task = background_task
        if self.only_run_first:
            tasks = [self.background_task.add_task(func_obj) for func_obj in self.tasks]
        else:
            tasks = [background_task.add_task(func_obj) for func_obj in self.tasks]
        return background_task

# import asyncio
# import time
#
# from fastapi import Depends
# from fastapi import Request
# from src.core.infirmary_controller import BaseHandler
# from src.core.infirmary_responses.orjson_response import Success, Fail
# from src.core.infirmary_tasks import BackgroundTasksDependency
# from src.modules.admin.modules.core_auth.infirmary_tasks import Tasks
#
#
# newtask = BackgroundTasksDependency(only_run_first=False)
# # 只会执行一次
# @newtask.on_task()
# async def _background_task_1():
#     print("background_task01")
#     await asyncio.sleep(1)
#     pass
#
# @newtask.on_task()
# def _background_task_2():
#     print("background_task02")
#     time.sleep(2)
#     pass
#
#
# class BackgroundTaskHandler(BaseHandler):
#
#     def __init__(
#             self,
#             request: Request,
#             infirmary_tasks: Tasks = Depends(newtask,use_cache=False)
#     ):
#         super().__init__(request)
#         self.infirmary_tasks = infirmary_tasks
#
#     @property
#     def response(self):
#         # 直接处理生成结果
#         return Success(result=[], message='测试验证后台任务')
